<template>
  <div class="random-quiz">
    <div class="page-header">
      <div class="header-top">
        <button class="back-btn" @click="$router.push('/challenge')">← 返回挑战</button>
        <h1>随机题目挑战</h1>
        <div class="timer">⏱️ {{ formatTime(remainingTime) }}</div>
      </div>
      <div class="progress-indicator">
        <div class="progress-text">第 1 题 / 共 1 题</div>
        <div class="progress-bar">
          <div class="progress-fill" style="width: 100%"></div>
        </div>
      </div>
    </div>
    
    <div class="quiz-content" v-if="question && question.question_id && !showResult">
      <div class="question-card">
        <h2>{{ question.content }}</h2>
        <div class="options">
          <div 
            class="option" 
            v-for="option in question.options" 
            :key="option.option_id"
            :class="{ selected: selectedOptionId === option.option_id }"
            @click="selectOption(option.option_id)"
          >
            <input 
              type="radio" 
              :id="'option' + option.option_id" 
              name="answer" 
              :value="option.option_id"
              :checked="selectedOptionId === option.option_id"
            >
            <label :for="'option' + option.option_id">{{ option.content }}</label>
          </div>
        </div>
        
        <div class="question-actions">
          <button 
            class="submit-btn" 
            @click="submitAnswer" 
            :disabled="selectedOptionId === null"
          >
            提交答案
          </button>
        </div>
      </div>
      
      <div class="quiz-info">
        <div class="info-card">
          <h3>挑战信息</h3>
          <p>📚 题目数量: 1题</p>
          <p>⭐ 奖励积分: 10碳积分</p>
          <p>⏱️ 时间限制: 无限制</p>
        </div>
      </div>
    </div>
    
    <!-- 添加结果显示区域 -->
    <div class="quiz-content" v-else-if="showResult && question && question.question_id">
      <div class="question-card">
        <h2>{{ question.content }}</h2>
        <div class="result-info">
          <div class="result-status" :class="{ correct: isCorrect, incorrect: !isCorrect }">
            <span v-if="isCorrect">✅ 答题正确</span>
            <span v-else>❌ 答题错误</span>
          </div>
          
          <div class="selected-answer">
            <p><strong>你的答案:</strong> {{ selectedOptionContent }}</p>
            <p v-if="!isCorrect"><strong>正确答案:</strong> {{ correctOptionContent }}</p>
          </div>
          
          <div class="explanation" v-if="explanation">
            <h3>解析:</h3>
            <p>{{ explanation }}</p>
          </div>
          
          <div class="score-info">
            <p>本次得分: {{ scoreEarned }}分</p>
            <p>总积分: {{ totalScore }}分</p>
          </div>
        </div>
        
        <div class="question-actions">
          <button class="next-btn" @click="returnToChallenge">返回挑战</button>
        </div>
      </div>
      
      <div class="quiz-info">
        <div class="info-card">
          <h3>挑战信息</h3>
          <p>📚 题目数量: 1题</p>
          <p>⭐ 奖励积分: 10碳积分</p>
          <p>⏱️ 时间限制: 无限制</p>
        </div>
      </div>
    </div>
    
    <div class="loading" v-else-if="loading">
      <p>正在加载题目...</p>
    </div>
    
    <div class="error" v-else-if="error">
      <p>加载题目失败: {{ error }}</p>
      <button class="retry-btn" @click="loadQuestion">重试</button>
    </div>
    
    <div class="empty" v-else>
      <p>暂无题目信息</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { submitAnswer as submitAnswerApi } from '../api/challenge'

// 路由
const router = useRouter()

// 数据状态
const question = ref<any>(null)
const selectedOptionId = ref<number | null>(null)
const loading = ref(true)
const error = ref('')
const remainingTime = ref(0)
let timer: number | null = null

// 结果显示相关状态
const showResult = ref(false)
const isCorrect = ref(false)
const scoreEarned = ref(0)
const selectedOptionContent = ref('')
const correctOptionContent = ref('')
const explanation = ref('')
const totalScore = ref(0)

// 格式化时间显示
const formatTime = (seconds: number) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 选择选项
const selectOption = (optionId: number) => {
  selectedOptionId.value = optionId
}

// 提交答案
const submitAnswer = async () => {
  try {
    // 检查是否有选中的答案
    if (selectedOptionId.value === null || !question.value) {
      showMessage('请选择一个答案','error')
      return
    }
    
    // 提交答案
    const response: any = await submitAnswerApi(question.value.question_id, selectedOptionId.value)
    
    // 检查响应是否成功
    if (response && response.success) {
      // 显示结果
      isCorrect.value = response.data?.is_correct || false
      scoreEarned.value = response.data?.score_earned || 0
      totalScore.value = response.data?.total_score || 0
      explanation.value = response.data?.explanation || ''
      correctOptionContent.value = response.data?.correct_option_content || ''
      selectedOptionContent.value = response.data?.selected_option_content || ''
      
      // 找到选中选项的内容
      if (!selectedOptionContent.value && question.value.options) {
        const selectedOption = question.value.options.find((opt: any) => opt.option_id === selectedOptionId.value)
        if (selectedOption) {
          selectedOptionContent.value = selectedOption.content
        }
      }
      
      showResult.value = true
    } else {
      const message = response && response.message ? response.message : '提交答案失败'
      showMessage('提交答案失败: ' + message,'error')
    }
  } catch (err: any) {
    console.error('[RandomQuiz] 提交答案失败:', err)
    showMessage('提交答案失败: ' + (err.message || '未知错误'),'error')
  }
}

const showMessage = (message: string, type: 'success' | 'error' = 'success') => {
  const toast = document.createElement('div')
  toast.textContent = message
  const base = 'position:fixed;left:50%;bottom:80px;transform:translateX(-50%);padding:10px 16px;border-radius:10px;color:#fff;box-shadow:0 6px 20px rgba(0,0,0,0.25);z-index:9999;font-size:14px;opacity:0.95;'
  const bg = type === 'success' ? 'background:#2E8B57;' : 'background:#E74C3C;'
  toast.setAttribute('style', base + bg)
  document.body.appendChild(toast)
  setTimeout(() => {
    toast.style.transition = 'opacity 0.3s ease'
    toast.style.opacity = '0'
    setTimeout(() => { toast.remove() }, 300)
  }, 1800)
}

// 返回挑战页面
const returnToChallenge = () => {
  router.push('/challenge')
}

// 加载题目
const loadQuestion = () => {
  try {
    // 从本地存储获取题目数据
    const questionData = localStorage.getItem('randomQuestion')
    if (questionData) {
      question.value = JSON.parse(questionData)
      loading.value = false
    } else {
      error.value = '未找到题目数据'
      loading.value = false
    }
  } catch (err: any) {
    console.error('[RandomQuiz] 加载题目失败:', err)
    error.value = err.message || '加载失败'
    loading.value = false
  }
}

// 启动计时器
const startTimer = () => {
  remainingTime.value = 10 * 60 // 10分钟
  timer = window.setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--
    } else {
      // 时间到，自动提交（如果有选择）
      if (selectedOptionId.value !== null && !showResult.value) {
        submitAnswer()
      }
      if (timer) clearInterval(timer)
    }
  }, 1000)
}

// 清理计时器
const clearTimer = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadQuestion()
  startTimer()
})

// 组件卸载时清理计时器
onUnmounted(() => {
  clearTimer()
})
</script>

<style scoped>
.random-quiz {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.header-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 1.8rem;
  margin: 0;
  color: #2c3e50;
  flex: 1;
  text-align: center;
  padding: 0 20px;
}

.back-btn, .timer {
  padding: 10px 20px;
  border-radius: 20px;
  font-weight: bold;
  white-space: nowrap;
}

.back-btn {
  background-color: #f8f9fa;
  color: #495057;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
}

.back-btn:hover {
  background-color: #e9ecef;
}

.timer {
  background-color: #42b983;
  color: white;
  display: flex;
  align-items: center;
  gap: 5px;
}

.progress-indicator {
  background-color: #f8f9fa;
  border-radius: 10px;
  padding: 15px;
  box-sizing: border-box;
}

.progress-text {
  text-align: center;
  margin-bottom: 10px;
  color: #495057;
  font-weight: 500;
}

.progress-bar {
  width: 100%;
  height: 12px;
  background-color: #e9ecef;
  border-radius: 6px;
  overflow: hidden;
  box-sizing: border-box;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #42b983, #2a8a64);
  border-radius: 6px;
}

.quiz-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 30px;
  max-width: 1200px;
  margin: 0 auto;
  box-sizing: border-box;
}

.question-card {
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  padding: 30px;
  box-sizing: border-box;
}

.question-card h2 {
  color: #2c3e50;
  margin-top: 0;
  margin-bottom: 30px;
  font-size: 1.5rem;
  line-height: 1.4;
}

.options {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 30px;
}

.option {
  padding: 15px 20px;
  border: 2px solid #e9ecef;
  border-radius: 10px;
  transition: all 0.3s;
  cursor: pointer;
}

.option:hover {
  border-color: #42b983;
  background-color: #f8f9fa;
}

.option.selected {
  border-color: #42b983;
  background-color: #e8f5ee;
}

.option input {
  margin-right: 15px;
}

.option label {
  cursor: pointer;
  font-size: 1.1rem;
  color: #495057;
}

.option input:checked + label {
  font-weight: bold;
  color: #2c3e50;
}

.option input:checked {
  accent-color: #42b983;
}

.question-actions {
  display: flex;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.submit-btn, .next-btn {
  padding: 12px 30px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 25px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.submit-btn:hover:not(:disabled), .next-btn:hover {
  background-color: #359c6d;
  transform: scale(1.05);
}

.submit-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quiz-info {
  align-self: start;
}

.info-card {
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  padding: 25px;
  box-sizing: border-box;
}

.info-card h3 {
  margin-top: 0;
  color: #2c3e50;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.info-card p {
  margin: 15px 0;
  color: #6c757d;
  display: flex;
  align-items: center;
  gap: 10px;
}

.loading, .error, .empty {
  text-align: center;
  padding: 40px 20px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.loading p, .error p, .empty p {
  margin: 0;
  color: #6c757d;
  font-size: 1.1rem;
}

.retry-btn {
  background-color: #ff6b35;
  color: white;
  padding: 10px 20px;
  border-radius: 20px;
  font-weight: bold;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 15px;
}

.retry-btn:hover {
  background-color: #e55a2b;
  transform: scale(1.05);
}

/* 新增的结果显示样式 */
.result-info {
  margin-bottom: 30px;
}

.result-status {
  font-size: 1.2rem;
  font-weight: bold;
  margin-bottom: 20px;
  padding: 10px;
  border-radius: 8px;
}

.result-status.correct {
  background-color: #e8f5ee;
  color: #42b983;
}

.result-status.incorrect {
  background-color: #fce8e8;
  color: #ff6b6b;
}

.selected-answer {
  margin-bottom: 20px;
}

.selected-answer p {
  margin: 10px 0;
  font-size: 1.1rem;
}

.explanation {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 10px;
  margin-bottom: 20px;
}

.explanation h3 {
  margin-top: 0;
  color: #2c3e50;
}

.explanation p {
  margin: 10px 0;
  line-height: 1.6;
  color: #495057;
}

.score-info {
  background-color: #e8f5ee;
  padding: 15px;
  border-radius: 8px;
}

.score-info p {
  margin: 8px 0;
  font-weight: 500;
  color: #42b983;
}

@media (max-width: 768px) {
  .quiz-content {
    grid-template-columns: 1fr;
  }
  
  .page-header h1 {
    font-size: 1.5rem;
    padding: 0 10px;
  }
  
  .question-card {
    padding: 20px;
  }
  
  .question-card h2 {
    font-size: 1.3rem;
  }
  
  .option {
    padding: 12px 15px;
  }
  
  .option label {
    font-size: 1rem;
  }
  
  .question-actions {
    flex-direction: column;
    gap: 15px;
  }
  
  .submit-btn, .next-btn {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .random-quiz {
    padding: 15px;
  }
  
  .page-header {
    padding: 15px;
  }
  
  .header-top {
    flex-direction: column;
    gap: 15px;
  }
  
  .page-header h1 {
    font-size: 1.3rem;
    padding: 0;
  }
  
  .back-btn, .timer {
    padding: 8px 15px;
    font-size: 0.9rem;
  }
  
  .question-card {
    padding: 15px;
  }
  
  .info-card {
    padding: 20px;
  }
}
</style>
